 <%@ page language="java" contentType="text/json; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.util.*, java.net.*, java.io.*, org.OpenGeoPortal.Solr.Searcher "%>
    
<%!

/**
 * This JSP reponds to all search requests from the client.
 * Results are returned in JSON format.
 * It checks for various parameters that specify the map extents, keywords, data type, data source
 *   date, publisher and collection.
 * It constructs a Solr query that potentially contains multipe fq (filter) clauses 
 *  along with a single q (search) clause.
 * 
 */
 

 /**
  * The following routines are used to construct the keyword search. They should be changed
  *   to use a filter and move to the Searcher class.
  */

public String createSearchComponent(HttpServletRequest request, String parameterName, String solrName)
{
	return createSearchComponent(request, parameterName, solrName, 2);
}

public String createSearchComponent(HttpServletRequest request, String parameterName, String solrName, float boostValue)
{

	String returnValue = "";
	String value = request.getParameter(parameterName);
	if (value == null) return returnValue;
	return createSearchComponent(value, solrName, boostValue);
}

public String createSearchComponent(String value, String solrName, float boostValue)
{
	String returnValue = "";
    value = value.trim();
	if (value.length() > 0)
 	{	
 		// add keyword search clause 
 		String[] values = value.split(" ");
        returnValue += Searcher.openParen;
        for (int i = 0 ; i < values.length ; i++)
        {
        	String currentValue = values[i];
        	if (i > 0)
        		returnValue += "+OR+";
        	returnValue += solrName + Searcher.colon + currentValue + "^" + boostValue;
        }
        returnValue += Searcher.closeParen;
	}
	return returnValue;
}

public String addSearchComponent(String baseString, String addedComponent)
{
	if (addedComponent.length() == 0) 
		return baseString;
	if (baseString.length() > 0) baseString += "+AND+"; 
		baseString += addedComponent;
	return baseString;
}

%>


<%

    String server = request.getServerName();
	//server = "geoportal-dev.atech.tufts.edu";
	String intersectionFilter = "";
 	int port = 8480;
	String solrQuery = "";
 	// add map related components if needed
	if (request.getParameter("minX") != null)
	{
		
		// here if we have location parameters to filter search
		double minX = Double.parseDouble(request.getParameter("minX"));
		double maxX = Double.parseDouble(request.getParameter("maxX"));
		double minY = Double.parseDouble(request.getParameter("minY"));
		double maxY = Double.parseDouble(request.getParameter("maxY"));
		Searcher searcher = new Searcher(minX, maxX, minY, maxY);
		solrQuery = searcher.geoSearch();
		intersectionFilter = searcher.layerIntersectsMapFilter();

	 }

 	 // handle basic search search term 
 	 
	 String searchTerm = request.getParameter("searchTerm");
	 System.out.println("searchTerm = " + searchTerm);
	    if (searchTerm == null)
	            searchTerm = "";
	    else
	    {
	    	    searchTerm = searchTerm.trim();
	            if (searchTerm.startsWith("Search "))
	                    searchTerm = "";  //field has "Search " as a prompt/default value, user didn't enter anything
	    }
	if (searchTerm.length() > 0)
	{
	    searchTerm = searchTerm.trim();
	 	String[] searchTerms = searchTerm.split(" ");
	    //keyword = keyword.replace(" ", "%20");
	    if (solrQuery != "")
	    	solrQuery += "+AND+";
	    solrQuery += Searcher.openParen;
	    for (int i = 0 ; i < searchTerms.length ; i++)
	    {
	    	String currentSearchTerm = searchTerms[i];
	     	if (i > 0)
	      		solrQuery += "+OR+";
	       	solrQuery += "LayerDisplayName" + Searcher.colon + currentSearchTerm + "^2";
	       	//solrQuery += "+OR+Institution" + Searcher.colon + currentSearchTerm + "^2";
	       	solrQuery += "+OR+Publisher" + Searcher.colon + currentSearchTerm;
	       	solrQuery += "+OR+Originator" + Searcher.colon + currentSearchTerm;
	       	//solrQuery += "+OR+DataType" + Searcher.colon + currentSearchTerm;
	       	solrQuery += "+OR+ThemeKeywords" + Searcher.colon + currentSearchTerm + "^2";
	       	solrQuery += "+OR+PlaceKeywords" + Searcher.colon + currentSearchTerm + "^2";
	       	//geoFilter += "+OR+Abstract" + Searcher.colon + "'" + currentKeyword + "'" + "^0.5";
	    }
	    solrQuery += Searcher.closeParen;
	}
		
	
		/*
		// new way to handle search term, not yet ready
	String searchTerm = request.getParameter("searchTerm");
	if (searchTerm == null) searchTerm = "";
	if (searchTerm.startsWith("Search "))
		searchTerm = "";
	searchTerm = searchTerm.trim();
	String keywordFilter = "";
	String keywordScore = "";
	if (searchTerm.length() > 0)
	{
		keywordFilter = Searcher.createBasicKeywordFilter(request);
		keywordScore = Searcher.createBasicKeywordScore(request);
		if (keywordScore != "")
		{
			if (solrQuery != "")
				solrQuery += "+AND+";
			solrQuery += keywordScore;
		}
	}
	*/

	// handle elements in the advanced search if present
	if ((request.getParameter("keyword") != null) && (request.getParameter("keyword") != ""))
	{
		if (solrQuery != "") solrQuery += "+AND+";
		solrQuery += Searcher.openParen;
		String themeKeywordSearch = createSearchComponent(request, "keyword", "ThemeKeywords", 10);
		solrQuery += themeKeywordSearch;
		String placeKeywordSearch = createSearchComponent(request, "keyword", "PlaceKeywords", 10);
		solrQuery += "+OR+" + placeKeywordSearch;
		String titleKeywordSearch = createSearchComponent(request, "keyword", "LayerDisplayName", 10);
		solrQuery += "+OR+" + titleKeywordSearch;
		
		solrQuery += Searcher.closeParen;
	}
	
	String publisherFilter = "";
	if ((request.getParameter("publisher") != null) && (request.getParameter("publisher") != ""))
	{
		publisherFilter = Searcher.createPublisherFilter(request);
	}
	
	//String collectionSearch = createSearchComponent(request, "collection", "CollectionId", 30);
	//solrQuery = addSearchComponent(solrQuery, collectionSearch);

	//String publisherSearch = createSearchComponent(request, "publisher", "Publisher");
	//solrQuery = addSearchComponent(solrQuery, publisherSearch);

	String dataTypeFilter = Searcher.createDataTypeFilter(request);
	String dataSourceFilter = Searcher.createDataSourceFilter(request); 
	String searchColumnsToReturn = Searcher.getColumnsForSearch();
	
	if (solrQuery == "")   // if we have no search clause yet, set it to search everything
		solrQuery = Searcher.asterik + Searcher.colon + Searcher.asterik;

	String solrResultsSubset = Searcher.resultSubset(request);
	String solrSortOrder = Searcher.sortOrder(request);
	String solrDateClause = Searcher.dateClause(request);
	System.out.println("solrDateClause = " + solrDateClause);
	

	String url$ = "http://" + server + ":" + port + "/solr/select/?q=" + solrQuery + "&debugQuery=off&version=2.2&" + solrResultsSubset
			+ "&rows=20&indent=on&wt=json&" + solrSortOrder;
 	if (intersectionFilter.length() > 0)
		url$ = url$ + "&fq=" + intersectionFilter;
 	if (solrDateClause.length() > 0)
 		url$ = url$ + "&fq=" + solrDateClause;
 	if (dataTypeFilter.length() > 0)
 		url$ = url$ + "&fq=" + dataTypeFilter;
 	if (dataSourceFilter.length() > 0)
 		url$ = url$ + "&fq=" + dataSourceFilter;
 	if (publisherFilter.length() > 0)
 		url$ = url$ + "&fq=" + publisherFilter;
 	//if (keywordFilter.length() > 0)
 	//	url$ = url$ + "&fq=" + keywordFilter;
 	 	
 	url$ = url$ + searchColumnsToReturn;
	System.out.println(" in solrSearchHandler, url = " + url$);
	URL url = new URL(url$);
	InputStream inputStream = url.openStream();
	InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
	BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
	String currentLine = bufferedReader.readLine();
	String json = "";
	while (currentLine != null)
	{
		currentLine = currentLine.replaceAll("\\n|\\r", " ");
		json = json + currentLine;
		if (currentLine.contains("LayerId"))
			System.out.println(currentLine);	
		currentLine = bufferedReader.readLine();
		
	}
	out.write(json);
	//System.out.println(json);
%>
